<template>
  <el-form ref="form" :model="cFrom" :inline="true" label-width="100px" :disabled="!isShowList">
    <el-form-item label="一级分类">
      <el-select placeholder="请选择品牌" v-model="cFrom.category1Id" @change="selectorCategory1">
        <el-option :label="c1.name" :value="c1.id" v-for="(c1,index) in category1List" :key="c1.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="二级分类">
      <el-select placeholder="请选择" v-model="cFrom.category2Id" @change="selectorCategory2">
        <el-option :label="c2.name" :value="c2.id" v-for="(c2,index) in category2List" :key="c2.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="三级分类">
      <el-select placeholder="请选择" v-model="cFrom.category3Id" @change="selectorCategory3">
        <el-option :label="c3.name" :value="c3.id" v-for="(c3,index) in category3List" :key="c3.id"></el-option>
      </el-select>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: "Category",
  props: ['isShowList'],
  data() {
    return {
      category1List: [],
      category2List: [],
      category3List: [],
      cFrom: {
        category1Id: '',
        category2Id: '',
        category3Id: ''
      },
    }
  },
  mounted() {
    this.getCategory1()
  },
  methods: {
    //获取1级分类
    async getCategory1() {
      try {
        const result = await this.$API.category.getCategory1()
        if (result.code === 200 || result.code === 20000) {
          this.category1List = result.data
        }
      } catch (error) {
        this.$message.error('获取一级分类失败')
      }
    },
    //根据1级分类的id获取二级分类
    async selectorCategory1(category1Id) {
      //重新选择1级的时候 需要清空选择框 2 3 的id级输入框
      this.category2List = [],
        this.category3List = [],
        this.cFrom.category2Id = "",
        this.cFrom.category3Id = ""

      try {
        const result = await this.$API.category.getCategory2(category1Id)
        // console.log(result)
        if (result.code === 200 || result.code === 20000) {
          this.category2List = result.data
          this.$emit('changeCategory', {categoryId: category1Id,level:1})
        }
      } catch (error) {
        this.$message.error('获取二级分类失败')
      }
    },
    //根据2级分类的id获取二级分类
    async selectorCategory2(category2Id) {
      //重新选择2级的时候 需要清空选择框 3 的id级输入框
        this.category3List = [],
        this.cFrom.category3Id = ""
      try {
        const result = await this.$API.category.getCategory3(category2Id)
        // console.log(result)
        if (result.code === 200 || result.code === 20000) {
          this.category3List = result.data
          this.$emit('changeCategory', {categoryId: category2Id,level:2})
        }
      } catch (error) {
        this.$message.error('获取二级分类失败')
      }
    },
    //根据3级分类的id 暂时不知道什么用途 先放在这里
    selectorCategory3(category3Id) {
      this.$emit('changeCategory', {categoryId: category3Id,level:3})
    }
  }
}
</script>

<style lang="less" scoped>

</style>
